package cn.changeforyou.ide.idea.plugin.utils;

import cn.changeforyou.ide.idea.plugin.MethodEditorContext;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.psi.util.PsiUtilBase;
import org.jetbrains.annotations.NotNull;

/**
 * @author zhyu
 * @date 2020/8/3 10:33
 */
public class EditorUtils {

    /**
     * 获取光标所在地的方法
     * @param anActionEvent
     * @return
     */
    @NotNull
    public static MethodEditorContext getPsiMethodWhichCursorIn(AnActionEvent anActionEvent) {
        Project project = anActionEvent.getProject();
        // 获取当前文件对象
        Editor editor = anActionEvent.getData(PlatformDataKeys.EDITOR);
        SelectionModel selectionModel = editor.getSelectionModel();
        int selectionStart = selectionModel.getSelectionStart();
        int selectionEnd = selectionModel.getSelectionEnd();
        PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
        MethodEditorContext context = new MethodEditorContext();
        context.setJavaFile(psiFile);
        for (PsiElement psiElement : psiFile.getChildren()) {
            System.out.println(psiElement);
            if (psiElement instanceof PsiClass) {
                PsiClass psiClass = (PsiClass) psiElement;
                context.setPsi_class(psiClass);
                PsiMethod[] methods = psiClass.getMethods();
                for (PsiMethod psiMethod : methods) {
                    TextRange textRange = psiMethod.getTextRange();
                    int startOffset = textRange.getStartOffset();
                    int endOffset = textRange.getEndOffset();
                    if (startOffset < selectionStart && endOffset > selectionEnd) {
                        context.setPsi_method(psiMethod);
                        return context;
                    }
                }
            }
        }
        return context;
    }
}
